package HttpPages;

import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;

import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.core.MediaType;

import C2DMRelated.C2DMMessage;
import C2DMRelated.C2DMSender;
import Database.Database;
import Logger.AppLogger;
import Objects.PendingMessage;

@Path("/sendTextMessage")
public class sendTextMessage 
{
	//-----------------------------------http methods--------------------------------

	// This method is called if TEXT_PLAIN is request
	@POST
	@Consumes(MediaType.TEXT_PLAIN)
	public String openConnectionRequest(@FormParam("my_android_id") String my_android_id,
			@FormParam("to_android_id") String to_android_id, @FormParam("message") String message,
			@FormParam("google_account") String google_account) //TODO need to remove if we id by androidId
	{
		AppLogger.write(Level.INFO, "Sending Request was recieved!");

		//finding in the database the corresponding C2DM registration_id of the destination of this message
		String to_registrationId = Database.getInstance().getC2DMRegistrationId(to_android_id);
		
		if(to_registrationId == null)
		{
			AppLogger.write(Level.WARNING, "The device '" + to_android_id + "' is not in the database!");
			return "The device 'to_android_id' is not in the database!";
		}
		
		PendingMessage newMessage = new PendingMessage(my_android_id, to_android_id, message);

		//adding the message to the database
		Database.getInstance().addPendingMessage(newMessage);
		
		//creating a new C2DM message that will be sent to the destination of this message
		Map<String, String> params = new HashMap<String, String>();
		params.put("message_id", "" + newMessage.get_message_id());		
		C2DMMessage newC2dmMessage = new C2DMMessage(C2DMMessage.MESSAGE_WAITING, params);
		
		//sending C2DM message to the client who needs to pull the message
		C2DMSender sender = new C2DMSender();
		sender.sendC2DMMessage("testing", to_registrationId, newC2dmMessage);
		
		//TODO  -  need to create Response codes file and handle everything!!!
		return "Sending message status: Delivered";
	}


}
